跳到主要内容

数据类型

最新的 ECMAScript 标准定义了 8 种数据类型:

7 种原始数据类型(又叫基本数据类型):

  • null,一个表明 null 值的特殊关键字。JavaScript 是大小写敏感的,因此 null 与 Null、NULL 或变体完全不同。
  • undefined,和 null 一样是一个特殊的关键字,undefined 表示变量未赋值时的属性。
  • Number 数字(),整数或浮点数,例如: 42 或者 3.14159。
  • String 字符串(),字符串是一串表示文本值的字符序列,例如:"Howdy"。
  • Boolean 布尔值(),有 2 个值分别是:true 和 false。
  • Symbol 代表(ECMAScript 6 中新添加的类型)。一种实例是唯一且不可改变的数据类型。
  • BigInt 任意精度的整数,可以安全地存储和操作大整数,甚至可以超过数字的安全整数限制。

复杂数据类型

  • 函数对象(Function)
  • 数组对象(Array)
  • 日期对象(Date)
  • 正则对象(RegExp)
  • 错误对象(Error)

类型检测

类型检测的方法:

  • typeof
  • instanceof
  • Object.prototype.toString
  • constructor
typeof undefined;
// "undefined"

typeof null;
// "object"

typeof 100;
// "number"

typeof NaN;
// "number"

typeof true;
// "boolean"

typeof "foo";
// "string"

typeof function () {};
// "function"

typeof [1, 2];
// "object"

typeof new Object();
// "object"
function Person() {}
function Student() {}
Student.prototype = new Person();
Student.prototype.constructor = Student;

const ben = new Student();
ben instanceof Student;
// true

const one = new Person();
one instanceof Person;
// true
one instanceof Student;
// false
ben instanceof Person;
// true
Obejct.prototype.toString.call(undefined)
// "[object Undefined]"

Obejct.prototype.toString.call(null)
// "[object Null]"

Obejct.prototype.toString.call(true)
// "[object Boolean]"

Obejct.prototype.toString.call('')
/// "[object String]"

Obejct.prototype.toString.call(123)
// "[object Number]"

Obejct.prototype.toString.call([])
// "[object Array]"

Obejct.prototype.toString.call({})
// "[object Object]"

数据类型的转换

JavaScript 是一种动态类型语言 (dynamically typed language)。这意味着你在声明变量时可以不必指定数据类型,而数据类型会在代码执行时会根据需要自动转换。 从 ECMAScript Standard 中了解 Number、String、Boolean、Array 和 Object 之间的相互转换会更加直观。

转换为布尔类型

// 显式类型转换
Boolean(mix)

// 在 逻辑判断 和 逻辑运算 时会隐式转换为 Boolean 类型。
!""; // 逻辑运算符
// true

undefined == null; // 相等运算符
// true

"2" > "10"; // 关系运算符
// true

数字转换为字符串

// 显式类型转换
toString(radix)
String(mix)

// 一元加法运算符
"37" - 7; // 30
"37" + 7; // "377"

字符串转换为数字

// 显式类型转换
Number(mix)
parseInt(string, radix)
parseFloat(string)
// 一元加法运算符
(+"1.1") + (+"1.1") = 2.2 // 注意:加入括号为清楚起见,不是必需的。